package cn.xuqiudong.backend.config.runner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;
import java.util.Set;

/**
 * 描述:
 * 打印requestMapping
 *
 * @author Vic.xu
 * @since 2025-02-10 17:45
 */
@Component
public class RequestMappingPrinterRunner implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestMappingPrinterRunner.class);

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * springboot启动时打印所有请求映射
     */
    @Value("${backend.print-mapping:false}")
    private boolean printMapping;

    @Override
    public void run(String... args) throws Exception {
        if (!printMapping) {
            return;
        }
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);

        // 获取所有的请求映射信息
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        LOGGER.info("========= Registered url size = {} start:===========================", handlerMethods.size());
        // 遍历请求映射信息的键值对
        for (Map.Entry<RequestMappingInfo, org.springframework.web.method.HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            org.springframework.web.method.HandlerMethod handlerMethod = entry.getValue();
            // 获取当前请求映射的所有 URL 模式
            Set<String> patternValues = requestMappingInfo.getPatternValues();
            // 遍历 URL 模式
            for (String pattern : patternValues) {
                // 获取处理方法
                LOGGER.debug("Mapped [{}] onto {} ", pattern, handlerMethod.getMethod());
            }
        }
        LOGGER.info("=========Registered url size = {} end;===========================", handlerMethods.size());

    }
}
